<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import Query from '@arcgis/core/rest/support/Query.js'
import { useUserStore } from '@/stores/user'
import type { FormInstance } from 'element-plus'
import { Search, Refresh, Edit, Check, Close, Filter, Message } from '@element-plus/icons-vue'

interface Issue {
  id: string
  facilityId: string
  facilityName: string
  date: string
  reporter_name: string
  type: string
  description: string
  status: string
  priority: string
  adminReply?: string
}

interface FacilityWithIssues {
  OBJECTID: number
  Name: string
  FacilityType: string
  address: string
  photo?: string
  issues: Issue[]
}

// 获取用户状态
const userStore = useUserStore()

// 状态变量
const facilities = ref<FacilityWithIssues[]>([])
const allIssues = ref<Issue[]>([])
const filteredIssues = ref<Issue[]>([])
const loading = ref(false)
const statusFilter = ref('all')
const showReplyDialog = ref(false)
const currentIssue = ref<Issue | null>(null)
const replyForm = reactive({
  reply: '',
  status: '已处理',
})
const replyFormRef = ref<FormInstance | null>(null)
const submitting = ref(false)

// 表单验证规则
const replyRules = {
  reply: [{ required: true, message: '请输入回复内容', trigger: 'blur' }],
}

// 地图和图层引用
let facilityLayer: FeatureLayer | null = null

onMounted(() => {
  loadFacilitiesAndIssues()
})

// 加载所有设施和问题
const loadFacilitiesAndIssues = async () => {
  loading.value = true
  try {
    // 创建设施图层
    facilityLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/7XPW9RycLUzz2YAj/arcgis/rest/services/SchoolFacilityManagement/FeatureServer/0',
      outFields: ['*'],
    })

    // 查询所有设施
    const query = new Query({
      where: '1=1', // 查询所有记录
      outFields: ['OBJECTID', 'Name', 'FacilityType', 'address', 'Issues'],
      returnGeometry: true,
    })

    const result = await facilityLayer.queryFeatures(query)

    // 处理查询结果
    facilities.value = []
    allIssues.value = []

    for (const feature of result.features) {
      const attrs = feature.attributes
      let issues: Issue[] = []

      // 解析JSON字符串字段
      try {
        if (attrs.Issues) {
          issues = JSON.parse(attrs.Issues)
        }
      } catch (error) {
        console.error('解析JSON数据失败:', error)
      }

      // 只添加有问题的设施
      if (issues.length > 0) {
        facilities.value.push({
          OBJECTID: attrs.OBJECTID,
          Name: attrs.Name || '未命名设施',
          FacilityType: attrs.FacilityType || '未知类型',
          address: attrs.address || '未知地址',
          issues: issues,
        })

        // 将问题添加到总问题列表
        allIssues.value.push(...issues)
      }
    }

    // 默认显示所有问题
    applyFilter()

    ElMessage.success(`成功加载 ${allIssues.value.length} 个问题报告`)
  } catch (error) {
    console.error('加载设施和问题失败:', error)
    ElMessage.error('加载设施和问题失败')
  } finally {
    loading.value = false
  }
}

// 应用筛选器
const applyFilter = () => {
  if (statusFilter.value === 'all') {
    filteredIssues.value = [...allIssues.value]
  } else {
    filteredIssues.value = allIssues.value.filter((issue) => issue.status === statusFilter.value)
  }
}

// 打开回复对话框
const openReplyDialog = (issue: Issue) => {
  currentIssue.value = issue
  replyForm.reply = issue.adminReply || ''
  replyForm.status = issue.status
  showReplyDialog.value = true
}

// 提交回复
const submitReply = async () => {
  if (!replyFormRef.value || !currentIssue.value) return

  await replyFormRef.value.validate(async (valid) => {
    if (valid && facilityLayer) {
      submitting.value = true
      try {
        // 查找包含此问题的设施
        const facility = facilities.value.find((f) =>
          f.issues.some((i) => i.id === currentIssue.value?.id),
        )

        if (!facility) {
          ElMessage.error('未找到相关设施')
          return
        }

        // 更新问题状态和回复
        const updatedIssues = facility.issues.map((issue) => {
          if (issue.id === currentIssue.value?.id) {
            return {
              ...issue,
              status: replyForm.status,
              adminReply: replyForm.reply,
            }
          }
          return issue
        })

        // 克隆设施要素
        let updatedFeature = { attributes: {} }

        // 更新要素属性
        updatedFeature!.attributes = {
          Issues: JSON.stringify(updatedIssues),
          OBJECTID: facility.OBJECTID, // 保留原始ID
        }

        // 应用编辑
        const results = await facilityLayer.applyEdits({
          updateFeatures: [updatedFeature! as Graphic],
        })

        if (results.updateFeatureResults.length > 0) {
          ElMessage.success('回复提交成功')

          // 更新本地数据
          facility.issues = updatedIssues

          // 更新总问题列表中的问题
          const index = allIssues.value.findIndex((i) => i.id === currentIssue.value?.id)
          if (index !== -1) {
            allIssues.value[index] = {
              ...allIssues.value[index],
              status: replyForm.status,
              adminReply: replyForm.reply,
            }
          }

          // 重新应用筛选
          applyFilter()

          // 关闭对话框
          showReplyDialog.value = false
        } else {
          ElMessage.error('回复提交失败')
        }
      } catch (error) {
        console.error('提交回复失败:', error)
        ElMessage.error('提交回复失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 刷新数据
const refreshData = () => {
  loadFacilitiesAndIssues()
}
</script>

<template>
  <div class="maintenance-container">
    <div class="page-header">
      <h2>设施问题维护</h2>
      <div class="header-actions">
        <el-select
          v-model="statusFilter"
          placeholder="按状态筛选"
          @change="applyFilter"
          class="filter-select"
        >
          <el-option label="全部问题" value="all" />
          <el-option label="待处理" value="待处理" />
          <el-option label="已处理" value="已处理" />
        </el-select>
        <el-button type="primary" @click="refreshData" :icon="Refresh">刷新数据</el-button>
      </div>
    </div>

    <el-card class="issues-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>问题列表</span>
          <el-tag type="info">共 {{ filteredIssues.length }} 个问题</el-tag>
        </div>
      </template>

      <el-empty v-if="filteredIssues.length === 0" description="暂无问题报告" />

      <el-table v-else :data="filteredIssues" style="width: 100%" class="issues-table">
        <el-table-column prop="facilityName" label="设施名称" min-width="120" />
        <el-table-column prop="date" label="报告日期" width="100" />
        <el-table-column prop="reporter_name" label="报告人" width="100" />
        <el-table-column prop="type" label="问题类型" width="100" />
        <el-table-column
          prop="description"
          label="问题描述"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.priority === '高'
                  ? 'danger'
                  : scope.row.priority === '中'
                    ? 'warning'
                    : 'info'
              "
            >
              {{ scope.row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '已处理' ? 'success' : 'warning'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="adminReply" label="回复" min-width="150" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.adminReply">{{ scope.row.adminReply }}</span>
            <el-tag v-else type="info" size="small">暂无回复</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              circle
              @click="openReplyDialog(scope.row)"
              :icon="Message"
              title="回复"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 回复对话框 -->
    <el-dialog v-model="showReplyDialog" title="回复问题" width="50%" destroy-on-close>
      <div v-if="currentIssue" class="issue-detail">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="设施名称">{{
            currentIssue.facilityName
          }}</el-descriptions-item>
          <el-descriptions-item label="报告人">{{
            currentIssue.reporter_name
          }}</el-descriptions-item>
          <el-descriptions-item label="问题类型">{{ currentIssue.type }}</el-descriptions-item>
          <el-descriptions-item label="优先级">{{ currentIssue.priority }}</el-descriptions-item>
          <el-descriptions-item label="报告日期">{{ currentIssue.date }}</el-descriptions-item>
          <el-descriptions-item label="当前状态">{{ currentIssue.status }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">{{
            currentIssue.description
          }}</el-descriptions-item>
        </el-descriptions>

        <el-form
          ref="replyFormRef"
          :model="replyForm"
          :rules="replyRules"
          label-width="100px"
          class="reply-form"
        >
          <el-form-item label="问题状态" prop="status">
            <el-radio-group v-model="replyForm.status">
              <el-radio label="待处理">待处理</el-radio>
              <el-radio label="已处理">已处理</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="回复内容" prop="reply">
            <el-input
              v-model="replyForm.reply"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showReplyDialog = false">取消</el-button>
          <el-button type="primary" @click="submitReply" :loading="submitting">提交回复</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.maintenance-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    color: #303133;
    font-size: 22px;
  }

  .header-actions {
    display: flex;
    gap: 10px;
    align-items: center;
  }

  .filter-select {
    width: 150px;
  }
}

.issues-card {
  margin-bottom: 20px;
  flex: 1;
  overflow: auto;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.issues-table {
  :deep(th) {
    background-color: #f5f7fa;
    color: #606266;
  }

  :deep(td) {
    padding: 8px 0;
  }
}

.issue-detail {
  margin-bottom: 20px;
}

.reply-form {
  margin-top: 20px;
}
</style>
